package com.zhx.core.social.qq.connect;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.social.oauth2.AccessGrant;
import org.springframework.social.oauth2.OAuth2Template;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;

/**
 * @author zhanghaixuan
 * @create 2017/11/25-下午6:02
 **/
public class QQAuth2Template extends OAuth2Template {

    private Logger logger = LoggerFactory.getLogger(getClass());

    public QQAuth2Template(String clientId, String clientSecret, String authorizeUrl, String accessTokenUrl) {
        super(clientId, clientSecret, authorizeUrl, (String)null, accessTokenUrl);
        setUseParametersForClientAuthentication(true);
    }

    @Override
    protected AccessGrant postForAccessGrant(String accessTokenUrl, MultiValueMap<String, String> parameters) {

        String s = getRestTemplate().postForObject(accessTokenUrl, parameters, String.class);

        logger.info("获取的QQ Auth2 响应为:" + s);

        String[] split = StringUtils.split(s, "&");

        String asscessToken = StringUtils.substringAfterLast(split[0].toString(),"=");
        Long expireTime = Long.parseLong(StringUtils.substringAfterLast(split[1].toString(),"="));
        String refushToken = StringUtils.substringAfterLast(split[2].toString(),"=");

        return new AccessGrant(asscessToken,null,refushToken,expireTime);
    }

    @Override
    protected RestTemplate createRestTemplate() {
        RestTemplate restTemplate = super.createRestTemplate();
        restTemplate.getMessageConverters().add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
        return restTemplate;
    }
}
